<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>AI 助手</title>
  <style>
    .ai-message h1,
    .ai-message h2,
    .ai-message h3,
    .ai-message h4,
    .ai-message h5,
    .ai-message h6 {
      margin-top: 10px;
      margin-bottom: 10px;
      font-weight: bold;
      color: #ffffff;
    }

    .ai-message h1 {
      font-size: 1.8em;
    }

    .ai-message h2 {
      font-size: 1.6em;
    }

    .ai-message h3 {
      font-size: 1.4em;
    }

    .ai-message h4 {
      font-size: 1.2em;
    }

    .ai-message ul,
    .ai-message ol {
      padding-left: 20px;
      margin: 10px 0;
    }

    .ai-message li {
      margin: 5px 0;
    }

    .ai-message p {
      margin: 10px 0;
    }

    .ai-message blockquote {
      border-left: 3px solid #6b55b4;
      padding-left: 10px;
      margin: 10px 0;
      color: #cccccc;
    }

    .ai-message code {
      background-color: rgba(0, 0, 0, 0.3);
      padding: 2px 4px;
      border-radius: 3px;
      font-family: monospace;
    }

    .ai-message pre {
      background-color: rgba(0, 0, 0, 0.3);
      padding: 10px;
      border-radius: 5px;
      overflow-x: auto;
    }

    .ai-message pre code {
      background-color: transparent;
      padding: 0;
    }

    .ai-message hr {
      border: 0;
      height: 1px;
      background-color: rgba(255, 255, 255, 0.3);
      margin: 15px 0;
    }

    .ai-message table {
      border-collapse: collapse;
      width: 100%;
      margin: 15px 0;
    }

    .ai-message th,
    .ai-message td {
      border: 1px solid rgba(255, 255, 255, 0.3);
      padding: 8px;
      text-align: left;
    }

    .ai-message th {
      background-color: rgba(107, 85, 180, 0.3);
    }

    .ai-message a {
      color: #9f8ce9;
      text-decoration: underline;
    }

    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      background-image: url("{{ url_for('static', filename='素材/背景图.png') }}");
      background-size: cover;
      background-position: center;
      color: white;
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }

    .header,
    .footer,
    .content,
    .search-container,
    .response-container {
      max-width: 100%;
      box-sizing: border-box;
    }

    .container {
      max-width: 100%;
      max-height: 100%;
      overflow: auto;
    }

    * {
      box-sizing: border-box;
    }

    .footer {
      display: flex;
      height: 80px;
      background-color: #1c023f;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      margin-top: auto;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%;
      z-index: 1000;
    }

    .header {
      display: flex;
      height: 90px;
      width: 100%;
      background-color: #1c023f;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
    }

    .header h1,
    .header p {
      margin: 0;
    }

    .search-container {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      background-color: rgba(129, 133, 173, 0.3);
      padding: 10px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      width: 95%;
      text-align: left;
      position: fixed;
      bottom: 10px;
      /* 控制距离底部的距离 */
      left: 50%;
      transform: translateX(-50%);
      margin: 0;
    }

    .search-bar {
      background: rgba(188, 185, 200, 0.3);
      border-radius: 10px;
      padding: 8px;
      display: flex;
      align-items: center;
      width: 95%;
      flex-direction: column;
      align-items: flex-end;
      min-height: 150px;
      position: fixed;
      /* 固定在页面底部 */
      bottom: 5px;
      /* 距离底部 5px */
      left: 50%;
      transform: translateX(-50%);
      justify-content: flex-end;
      margin-bottom: 85px;
      transition: opacity 0.3s ease, visibility 0.3s ease;
    }

    .search-bar.hidden {
      opacity: 0;
      visibility: hidden;
    }

    .search-input {
      background: transparent;
      border: none;
      color: white;
      outline: none;
      flex: 1;
      margin-left: 10px;
      margin-right: 10px;
      padding: 5px;
      white-space: pre-wrap;
      word-wrap: break-word;
      overflow-wrap: break-word;
      width: 100%;
      resize: none;
      min-height: 50px;
      height: auto;
      align-self: flex-end;
      font-size: 20px;
    }

    .search-button {
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
      padding: 5px 15px;
      margin-left: 10px;
      transition: background-color 0.3s;
      right: 0;
      bottom: 2;
      position: absolute;
    }

    .search-button:hover {
      background: #4a3f8c;
    }

    .button {
      background: rgba(107, 85, 180, 0.7);
      opacity: 0.6;
      border: none;
      border-radius: 10px;
      color: white;
      padding: 12px;
      text-align: center;
      margin: 10px 20px;
      cursor: pointer;
    }

    .button:hover {
      background: #5b4aa3;
    }

    button img {
      display: block;
      max-width: 100%;
      height: auto;
    }

    .footer svg {
      color: white;
      font-size: 24px;
    }

    .back-btn,
    .location-btn,
    .calendar-btn,
    .moon-btn,
    .data-btn,
    .index-btn,
    .search-button {
      margin-right: 10px;
      background: none;
      border: none;
      padding: 0;
      cursor: pointer;
    }

    .location-info {
      flex-grow: 1;
      text-align: right;
      padding: 30px;
    }

    .location-info h1,
    .location-info p {
      margin: 0;
    }

    .content {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      background-color: rgba(129, 133, 173, 0.3);
      padding: 10px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      width: 95%;
      text-align: left;
      margin: 10px;
      margin-left: auto;
      margin-right: auto;
      flex: 4;
      position: relative;
    }

    .search-container {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      background-color: rgba(129, 133, 173, 0.3);
      padding: 10px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      width: 97%;
      text-align: left;
      position: fixed;
      bottom: 10px;
      /* 控制距离底部的距离 */
      left: 50%;
      transform: translateX(-50%);
      margin: 0;
    }

    .content {
      min-height: 58vh;
      overflow-y: auto;
      margin-bottom: 85px;
    }

    #response-container {
      padding: 15px;
      line-height: 1.6;
      white-space: pre-wrap;
    }

    .loading {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: #fff;
      animation: spin 1s ease-in-out infinite;
      margin-left: 10px;
    }

    @keyframes spin {
      to {
        transform: rotate(360deg);
      }
    }

    .chat-history {
      margin-bottom: 160px;
    }

    .chat-message {
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 8px;
    }

    .user-message {
      background-color: rgba(91, 74, 163, 0.5);
      align-self: flex-end;
      margin-left: 20%;
    }

    .ai-message {
      background-color: rgba(45, 45, 45, 0.5);
      align-self: flex-start;
      margin-right: 20%;
    }

    .model-selector {
      margin: 10px 0;
      padding: 5px;
      background: rgba(45, 45, 45, 0.5);
      color: white;
      border: none;
      border-radius: 5px;
    }
  </style>
</head>

<body>
  <div class="header">
    <button class="back-btn" onclick="window.location.href='newai.html'">
      <img src="{{ url_for('static', filename='素材/left.png') }}" alt="Back" />
    </button>
    <div class="location-info">
      <h4 id="location-name">北京</h4>
      <p id="coordinates">116.4074°E 39.9042°N</p>
    </div>
    <button class="location-btn" onclick="window.location.href='direction.html'">
      <img src="{{ url_for('static', filename='素材/箭头.png') }}" alt="Location" />
    </button>
  </div>

  <div class="content">
    <div id="chat-history" class="chat-history">
      <!-- 聊天历史将在这里显示 -->
    </div>
  </div>

  <div class="search-bar" id="search-bar">
    <textarea id="question" class="search-input" placeholder="输入你的问题..." onkeypress="handleKeyPress(event)"
      rows="4"></textarea>

    <!-- 模型选择下拉框 -->
    <!-- <select id="model-selector" class="model-selector">
      <option value="default">默认模型 (deepseek-r1:14b)</option>
      <option value="small">小模型 (deepseek-codex-small:0.9b)</option>
      <option value="large">大模型 (deepseek-codex-large:1.7b)</option>
    </select> -->

    <button class="search-button" onclick="askQuestion()" id="submit-button">
      <img src="{{ url_for('static', filename='素材/箭头.png') }}" alt="提交" />
    </button>
  </div>

  <div class="footer">
    <button class="calendar-btn" onclick="window.location.href='newcalendar.html'">
      <img src="{{ url_for('static', filename='素材/日历浅色.png') }}" alt="calendar" />
    </button>
    <button class="moon-btn" onclick="window.location.href='十二宫图.html'">
      <img src="{{ url_for('static', filename='素材/可视化浅色.png') }}" alt="moon" />
    </button>
    <button class="data-btn" onclick="window.location.href='newdata.html'">
      <img src="{{ url_for('static', filename='素材/知识浅色.png') }}" alt="data" />
    </button>
    <button class="index-btn" onclick="window.location.href='newai.html'">
      <img src="{{ url_for('static', filename='素材/大模型深色.png') }}" alt="index" />
    </button>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

  <script>
    // 全局变量
    let chatHistory = [];

    // 页面加载时执行
    window.onload = function () {
      // 从本地存储加载位置信息
      if (
        localStorage.getItem("locationName") &&
        localStorage.getItem("coordinates")
      ) {
        document.getElementById("location-name").innerText =
          localStorage.getItem("locationName");
        document.getElementById("coordinates").innerText =
          localStorage.getItem("coordinates");
      }

      // 从本地存储加载聊天历史
      const savedHistory = localStorage.getItem("chatHistory");
      if (savedHistory) {
        chatHistory = JSON.parse(savedHistory);
        displayChatHistory();
      }

      // 聚焦到输入框
      document.getElementById("question").focus();
    };

    // 处理回车键按下事件
    function handleKeyPress(event) {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        askQuestion();
      }
    }

    // 隐藏输入框
    function hideInputBox() {
      const searchBar = document.getElementById("search-bar");
      searchBar.classList.add("hidden");
    }

    // 显示输入框
    function showInputBox() {
      const searchBar = document.getElementById("search-bar");
      searchBar.classList.remove("hidden");
    }

    // 向后端发送问题并获取回答
    async function askQuestion() {
      const inputElement = document.getElementById("question");
      const question = inputElement.value.trim();

      if (!question) {
        alert("请输入一个问题");
        return;
      }

      // 禁用输入和按钮，防止重复提交
      inputElement.disabled = true;
      const submitButton = document.getElementById("submit-button");
      submitButton.disabled = true;

      // 隐藏输入框
      hideInputBox();

      // 添加用户问题到聊天历史
      addMessageToChat(question, "user");

      // 添加AI正在思考的消息
      const thinkingId = addThinkingMessage();

      try {
        const response = await fetch("/ask", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ question }),
        });

        if (!response.ok) {
          throw new Error(`服务器返回错误: ${response.status}`);
        }

        const data = await response.json();

        // 移除"正在思考"消息
        removeThinkingMessage(thinkingId);

        // 添加AI回答到聊天历史
        addMessageToChat(data.answer, "ai");

        // 保存聊天历史到本地存储
        saveChatHistory();
      } catch (error) {
        console.error("API错误:", error);

        // 移除"正在思考"消息
        removeThinkingMessage(thinkingId);

        // 添加错误消息
        addMessageToChat(`获取回答时出错: ${error.message}`, "ai");
      } finally {
        // 重新启用输入和按钮
        inputElement.disabled = false;
        submitButton.disabled = false;

        // 清空输入框并聚焦
        inputElement.value = "";

        // 显示输入框
        showInputBox();

        // 聚焦到输入框
        setTimeout(() => {
          inputElement.focus();
        }, 300); // 等待显示动画完成后聚焦
      }
    }

    // 添加消息到聊天界面
    function addMessageToChat(message, sender) {
      const chatHistoryElement = document.getElementById("chat-history");
      const messageElement = document.createElement("div");

      messageElement.classList.add("chat-message");
      messageElement.classList.add(
        sender === "user" ? "user-message" : "ai-message"
      );

      // 处理markdown格式
      if (sender === "ai") {
        // 使用marked库来解析Markdown
        messageElement.innerHTML = marked.parse(message);
      } else {
        messageElement.textContent = message;
      }

      chatHistoryElement.appendChild(messageElement);

      // 保存到聊天历史数组
      chatHistory.push({ message, sender });

      // 滚动到底部
      scrollToBottom();
    }

    // 显示聊天历史
    function displayChatHistory() {
      const chatHistoryElement = document.getElementById("chat-history");
      chatHistoryElement.innerHTML = "";

      chatHistory.forEach((item) => {
        const messageElement = document.createElement("div");
        messageElement.classList.add("chat-message");
        messageElement.classList.add(
          item.sender === "user" ? "user-message" : "ai-message"
        );

        // 使用marked库解析Markdown
        if (item.sender === "ai") {
          messageElement.innerHTML = marked.parse(item.message);
        } else {
          messageElement.textContent = item.message;
        }

        chatHistoryElement.appendChild(messageElement);
      });

      // 滚动到底部
      scrollToBottom();
    }

    // 添加"正在思考"消息
    function addThinkingMessage() {
      const chatHistoryElement = document.getElementById("chat-history");
      const thinkingElement = document.createElement("div");
      const id = Date.now();

      thinkingElement.id = `thinking-${id}`;
      thinkingElement.classList.add("chat-message", "ai-message");

      const textSpan = document.createElement("span");
      textSpan.textContent = "正在思考";
      thinkingElement.appendChild(textSpan);

      const loadingSpan = document.createElement("span");
      loadingSpan.classList.add("loading");
      thinkingElement.appendChild(loadingSpan);

      chatHistoryElement.appendChild(thinkingElement);

      // 滚动到底部
      scrollToBottom();

      return id;
    }

    // 移除"正在思考"消息
    function removeThinkingMessage(id) {
      const thinkingElement = document.getElementById(`thinking-${id}`);
      if (thinkingElement) {
        thinkingElement.remove();
      }
    }

    // 显示聊天历史
    function displayChatHistory() {
      const chatHistoryElement = document.getElementById("chat-history");
      chatHistoryElement.innerHTML = "";

      chatHistory.forEach((item) => {
        const messageElement = document.createElement("div");
        messageElement.classList.add("chat-message");
        messageElement.classList.add(
          item.sender === "user" ? "user-message" : "ai-message"
        );

        // 修复这里的错误，使用item中的变量
        if (item.sender === "ai") {
          let formattedMessage = item.message
            .replace(/\n/g, "<br>")
            .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
            .replace(/###\s+(.*?)(\n|$)/g, "<h3>$1</h3>");
          messageElement.innerHTML = formattedMessage;
        } else {
          messageElement.textContent = item.message;
        }

        chatHistoryElement.appendChild(messageElement);
      });

      // 滚动到底部
      scrollToBottom();
    }

    // 保存聊天历史到本地存储
    function saveChatHistory() {
      localStorage.setItem("chatHistory", JSON.stringify(chatHistory));
    }

    // 滚动到底部
    function scrollToBottom() {
      const content = document.querySelector(".content");
      content.scrollTop = content.scrollHeight;
    }

    // 自动调整文本区域高度
    const textarea = document.getElementById("question");
    textarea.addEventListener("input", function () {
      this.style.height = "auto";
      this.style.height = this.scrollHeight + "px";
    });
  </script>
</body>

</html>